import cn.hutool.db.ds.simple.SimpleDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class MysqlFetcher {
    
    public static List<String> getNameList(String connectPropStr) {
        List<String> list = new ArrayList<>();
        String[] connectProps = connectPropStr.split(",");
        String url = String.format("jdbc:mysql://%s:3306/%s", connectProps[0], connectProps[3]);
        String username = connectProps[1];
        String password = connectProps[2];
        try (SimpleDataSource dataSource = new SimpleDataSource(url, username, password)) {
            
            try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement("select name from student")) {
                boolean success = statement.execute();
                if (success) {
                    ResultSet resultSet = statement.getResultSet();
                    while (resultSet.next()) {
                        String name = resultSet.getString("name");
                        list.add(name);
                    }
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
    
    public static boolean tryConnect(String connectPropStr) {
        String[] connectProps = connectPropStr.split(",");
        String url = String.format("jdbc:mysql://%s:3306/%s", connectProps[0], connectProps[3]);
        String username = connectProps[1];
        String password = connectProps[2];
        try (SimpleDataSource dataSource = new SimpleDataSource(url, username, password)) {
            
            try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement("select 1")) {
                return statement.execute();
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    
}
